import React, { useState, useEffect, useRef, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { Heart, HeartCrack } from 'lucide-react'
import {
  addLike,
  removeLike,
  updateLike,
  getLikeByEntityIdAndSelf,
  getLikeByEntityId
} from '@/apis/recommend'
import type { Likes } from '@/types/recommend'

interface LikeButtonProps {
  entityId: string
  entityType: number
  onLikeChange?: (data: {
    likesCount: number
    dislikesCount: number
    userLike: Likes | null
  }) => void
}

const LikeButton: React.FC<LikeButtonProps> = ({
  entityId,
  entityType,
  onLikeChange
}) => {
  const [likesCount, setLikesCount] = useState(0)
  const [dislikesCount, setDislikesCount] = useState(0)
  const [userLike, setUserLike] = useState<Likes | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const isMounted = useRef(false)

  // 获取用户当前点赞状态和点赞总数
  const fetchLikeStatus = useCallback(async () => {
    if (!entityId || !entityType) return

    try {
      const response = await getLikeByEntityIdAndSelf(entityType, entityId)

      // 获取总的点赞数和点踩数
      const likesResponse = await getLikeByEntityId(
        entityType,
        entityId,
        1 // 获取点赞
      )

      const dislikesResponse = await getLikeByEntityId(
        entityType,
        entityId,
        2 // 获取点踩
      )

      // 设置点赞和点踩数量
      setLikesCount(likesResponse?.total || 0)
      setDislikesCount(dislikesResponse?.total || 0)

      if (response?.items && response.items.length > 0) {
        const like = response.items[0]
        setUserLike(like)
      } else {
        setUserLike(null)
      }
    } catch (err) {
      console.error('Failed to fetch like status:', err)
      setError('Failed to load like status')
    }
  }, [entityId, entityType])

  useEffect(() => {
    if (!isMounted.current) {
      isMounted.current = true
      fetchLikeStatus()
    }

    return () => {
      isMounted.current = false
    }
  }, [entityId, entityType, fetchLikeStatus])

  // 处理点赞操作
  const handleLike = async () => {
    if (loading) return

    setLoading(true)
    setError(null)

    try {
      let newLikesCount = likesCount
      let newDislikesCount = dislikesCount
      let newUserLike: Likes | null = userLike

      if (userLike) {
        if (userLike.type === 1) {
          // 用户已经点赞，取消点赞
          await removeLike(userLike.id!)
          newLikesCount = likesCount - 1
          newUserLike = null
        } else if (userLike.type === 2) {
          // 用户已经点踩，改为点赞
          const updatedLike = await updateLike(
            userLike.id!,
            entityType,
            entityId,
            1
          )
          newLikesCount = likesCount + 1
          newDislikesCount = dislikesCount - 1
          newUserLike = updatedLike
        }
      } else {
        // 用户尚未操作，直接添加点赞状态的数据
        const newLike = await addLike(entityType, entityId, 1)
        newLikesCount = likesCount + 1
        newUserLike = newLike
      }

      setLikesCount(newLikesCount)
      setDislikesCount(newDislikesCount)
      setUserLike(newUserLike)
      onLikeChange?.({
        likesCount: newLikesCount,
        dislikesCount: newDislikesCount,
        userLike: newUserLike
      })
    } catch (err) {
      console.error('Failed to update like status:', err)
      setError('Failed to update like status')
    } finally {
      setLoading(false)
    }
  }

  // 处理点踩操作
  const handleDislike = async () => {
    if (loading) return

    setLoading(true)
    setError(null)

    try {
      let newLikesCount = likesCount
      let newDislikesCount = dislikesCount
      let newUserLike: Likes | null = userLike

      if (userLike) {
        if (userLike.type === 2) {
          // 用户已经点踩，取消点踩
          await removeLike(userLike.id!)
          newDislikesCount = dislikesCount - 1
          newUserLike = null
        } else if (userLike.type === 1) {
          // 用户已经点赞，改为点踩
          const updatedLike = await updateLike(
            userLike.id!,
            entityType,
            entityId,
            2
          )
          newLikesCount = likesCount - 1
          newDislikesCount = dislikesCount + 1
          newUserLike = updatedLike
        }
      } else {
        // 用户尚未操作，直接添加点踩状态的数据
        const newLike = await addLike(entityType, entityId, 2)
        newDislikesCount = dislikesCount + 1
        newUserLike = newLike
      }

      setLikesCount(newLikesCount)
      setDislikesCount(newDislikesCount)
      setUserLike(newUserLike)
      onLikeChange?.({
        likesCount: newLikesCount,
        dislikesCount: newDislikesCount,
        userLike: newUserLike
      })
    } catch (err) {
      console.error('Failed to update dislike status:', err)
      setError('Failed to update dislike status')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="flex items-center space-x-2">
      <div className="flex">
        <Button
          variant="ghost"
          size="sm"
          onClick={handleLike}
          disabled={loading}
          className={`flex h-auto items-center gap-1 rounded-full p-2 ${
            userLike?.type === 1
              ? 'bg-red-50 text-red-500'
              : 'text-gray-500 hover:text-red-500'
          }`}
        >
          <Heart
            className="size-5"
            fill={userLike?.type === 1 ? 'currentColor' : 'none'}
          />
          <span className="text-xs">{likesCount}</span>
        </Button>
      </div>

      <div className="flex">
        <Button
          variant="ghost"
          size="sm"
          onClick={handleDislike}
          disabled={loading}
          className={`flex h-auto items-center gap-1 rounded-full p-2 ${
            userLike?.type === 2
              ? 'bg-blue-100 text-blue-500 hover:bg-blue-100'
              : 'text-gray-500 hover:text-blue-500'
          }`}
        >
          <HeartCrack className="size-5 text-current" />
          <span className="text-xs">{dislikesCount}</span>
        </Button>
      </div>

      {error && <span className="text-xs text-red-500">{error}</span>}
    </div>
  )
}

export default LikeButton
